package com.cong.cojcodesandbox;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.dfa.WordTree;
import com.cong.cojcodesandbox.mode.ExecuteCodeRequest;
import com.cong.cojcodesandbox.mode.ExecuteCodeResponse;
import com.cong.cojcodesandbox.mode.ExecuteMessage;
import com.cong.cojcodesandbox.mode.JudgeInfo;
import com.cong.cojcodesandbox.utils.ProcessUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * Java 代码沙盒模板
 *
 * @author 86188
 * @date 2023/10/22
 */
@Slf4j
public abstract class JavaCodeSandboxTemplate implements CodeSandbox {

    public static final String GLOBAL_CODE_DIR_NAME = "tempCode";
    public static final String GLOBAL_JAVA_CLASS_NAME = "Main.java";
    private static final long TIME_OUT =  5000L;

    /**
     * 执行代码
     *
     * @param executeCodeRequest 执行代码请求
     * @return {@link ExecuteCodeResponse}
     */
    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {

        List<String> inputList = executeCodeRequest.getInputList();
        String code = executeCodeRequest.getCode();
        //1、把用户代码保存为文件
        File userCodeFile = saveCodeToFile(code);
        //2、编译代码得到class文件
        ExecuteMessage compileFileExecuteMessage = compileFile(userCodeFile);
        System.out.println(compileFileExecuteMessage);
        //3、执行文件，获取输出结果
        List<ExecuteMessage> executeMessageList = runFile(userCodeFile, inputList);

        //4、整理输出结果
        ExecuteCodeResponse executeCodeResponse = getOutputResponse(executeMessageList);

        //5、文件清理 防止服务器空间不足
        boolean b = deleteFile(userCodeFile);
        if (!b){
            log.error("deleteFile error, userCodeFilePath = {}",userCodeFile.getAbsolutePath());
        }

        return executeCodeResponse;
    }

    /**
     * 1、将代码保存到文件
     *
     * @param code 用户代码
     * @return {@link File}
     */
    public File saveCodeToFile(String code){
        String userDir = System.getProperty("user.dir");
        String globalCodePathName = userDir+ File.separator + GLOBAL_CODE_DIR_NAME;
        //判断全局代码目录是否存在,没有则新建
        if (FileUtil.exist(globalCodePathName)){
            FileUtil.mkdir(globalCodePathName);
        }
        //把用户代码隔离存放
        String userCodeParentPath = globalCodePathName + File.separator + UUID.randomUUID();
        String userCodePath = userCodeParentPath + File.separator + GLOBAL_JAVA_CLASS_NAME;
        File userCodeFile = FileUtil.writeString(code, userCodePath, StandardCharsets.UTF_8);
        return userCodeFile;
    }

    /**
     * 编译文件代码
     *
     * @param userCodeFile 用户代码文件
     * @return {@link ExecuteMessage}
     */
    public ExecuteMessage compileFile(File userCodeFile){
        //编译代码，得到class文件
        String compileCmd = String.format("javac -encoding utf-8 %s",userCodeFile.getAbsolutePath());
        Process compileProcess = null;
        try {
            compileProcess = Runtime.getRuntime().exec(compileCmd);
            ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(compileProcess, "编译");
            if (executeMessage.getExitValue()!=0){
                throw new RuntimeException("编译错误");
            }
            return executeMessage;

        } catch (Exception e) {
//            return getResponse(e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 运行文件
     *
     * @param userCodeFile 用户代码文件
     * @param inputList    输入列表
     * @return {@link List}<{@link ExecuteMessage}>
     */
    public List<ExecuteMessage> runFile(File userCodeFile,List<String> inputList){
        String userCodeParentPath = userCodeFile.getParentFile().getAbsolutePath();
        //执行代码获取输出结果
        List<ExecuteMessage> executeMessageList = new ArrayList<>();

        for (String inputArg : inputList) {
            String runCmd = String.format("java -Xmx256m -Dfile.encoding=utf-8 -cp %s Main %s", userCodeParentPath, inputArg);
            try {
                Process runProcess = Runtime.getRuntime().exec(runCmd);;
                //超时控制
                new Thread(()->{
                    try {
                        Thread.sleep(TIME_OUT);
                        System.out.println("超时了，中断");
                        runProcess.destroy();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }).start();
                ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(runProcess, "运行");
//            ExecuteMessage executeMessage = ProcessUtils.runInteractProcessAndGetMessage(runCmd, "运行",inputArg);

                System.out.println(executeMessage);
                executeMessageList.add(executeMessage);
            } catch (Exception e) {
               throw new RuntimeException("程序执行异常",e);
            }
        }
        return executeMessageList;
    }

    /**
     * 获取输出响应
     *
     * @param executeMessageList 执行消息列表
     * @return {@link ExecuteCodeResponse}
     */
    public ExecuteCodeResponse getOutputResponse(List<ExecuteMessage> executeMessageList){
        //收集整理输出结果
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        List<String> outputList = new ArrayList<>();
        //取用时最大值，便于判断是否超时
        Long maxTime =0L;
        for (ExecuteMessage executeMessage : executeMessageList) {
            //错误信息不为空
            if (StrUtil.isNotBlank(executeMessage.getErrorMessage())){
                executeCodeResponse.setMessage(executeMessage.getErrorMessage());
                //用户提交代码执行中存在错误
                executeCodeResponse.setStatus(3);
                break;
            }
            outputList.add(executeMessage.getMessage());
            Long time =  executeMessage.getTime();
            if (time != null){
                maxTime = Math.max(maxTime,time);
            }
        }
        //正常运行
        if (outputList.size() == executeMessageList.size()) {
            executeCodeResponse.setStatus(1);
        }
        executeCodeResponse.setOutputList(outputList);
        JudgeInfo judgeInfo = new JudgeInfo();
        //要用到第三方库十分麻烦 暂不实现
        //judgeInfo.setMemoryLimit();
        judgeInfo.setTime(maxTime);
        executeCodeResponse.setJudgeInfo(judgeInfo);
        return executeCodeResponse;
    }

    /**
     * 删除文件
     *
     * @param userCodeFile 用户代码文件
     * @return boolean
     */
    public boolean deleteFile(File userCodeFile){
        String userCodeParentPath = userCodeFile.getParentFile().getAbsolutePath();

        if (userCodeFile.getParentFile() !=null){
            boolean result = FileUtil.del(userCodeParentPath);
            System.out.println("删除" +(result?"成功":"失败"));
            return result;
        }
        return true;
    }



    /**
     * 获取错误相应
     * @param throwable
     * @return
     */
    private ExecuteCodeResponse getResponse(Throwable throwable){
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        executeCodeResponse.setOutputList(new ArrayList<>());
        executeCodeResponse.setMessage(throwable.getMessage());
        //代码沙箱执行错误
        executeCodeResponse.setStatus(2);
        executeCodeResponse.setJudgeInfo(new JudgeInfo());
        return executeCodeResponse;

    }
}
